package heap

import "unicode/utf16"

var internedStrings = map[string]*Object{}

// 将go语言的string转换为java的String类实例
func JavaString(loader *ClassLoader, go_string string) *Object {
	if internedString, ok := internedStrings[go_string]; ok {
		return internedString
	}
	chars := StringToUtf16(go_string)
	// 新建一个char数组
	java_char_array := &Object{
		class: loader.LoadClass("[C"),
		data: chars,
	}
	java_string_class := loader.LoadClass("java/lang/String")
	java_string_object := java_string_class.NewObject()
	java_string_object.SetRefVar("value", "[C", java_char_array)

	internedStrings[go_string] = java_string_object
	return java_string_object
}

func StringToUtf16(go_string string) []uint16 {
	runes := []rune(go_string)
	return utf16.Encode(runes)
}

func Utf16ToString(value []uint16) string {
	decode := utf16.Decode(value)
	return string(decode)
}
